<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button flex felx_align">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="btnaddBrand">添加</el-button>
        <el-button type="primary" size="mini" @click="handleDownload">应用白名单辅助管理模板<i class="el-icon-paperclip el-icon--right"></i></el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="归属" value="username"></el-option>
              <el-option label="批次" value="batch"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- 设备归属管理table -->
    <el-table stripe style="width: 100%" :data="tableData" :key="key" border fit highlight-current-row ref="tableDataRef" max-height="545">
      <el-table-column v-if="colData[0].istrue" min-width="110" align="center" prop="username" label="归属"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="110" align="center" prop="batch" label="批次"></el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="160" align="center" prop="package_name" label="包名"></el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="140" align="center" prop="create_time" label="创建时间">
        <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column min-width="150" align="center" prop="log" label="操作">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="getqueryIdWhiteApp(scope.row.id)">编辑</el-button>
            <el-button size="mini" @click="deleteShow(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>

    <!-- 添加start -->
    <el-dialog title="应用安装白名单" :visible.sync="permitFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="30%" @close="addFormclose">
      <div style="margin-left:30px;color:#F56C6C" v-show="!editSubjects">若需要编辑，重新上传的数据会覆盖之前部署策略。</div>
      <el-form :model="addForm">
        <el-form-item label="选择类型:" label-width="100px" v-show="false">
          <el-radio-group v-model="addForm.type" :disabled="!editSubjects">
            <!-- <el-radio :label="1">单个包名</el-radio> -->
            <el-radio :label="2">多个包名</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="批次:" label-width="100px" prop="batch">
          <el-select v-model="addForm.batch" placeholder="请选择批次" class="add_select">
            <el-option v-for="item in lotoptions" :key="item.id" :label="item.batch" :value="item.id.toString()"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="添加包名:" label-width="100px" prop="package" v-if="!typeControl">
          <el-input v-model="addForm.package" placeholder="请输入包名"></el-input>
        </el-form-item>
        <el-form-item label="导入文件" label-width="100px" class="snElsx" v-if="typeControl">
          <div class="">
            <el-input autocomplete="off" placeholder="请点击上传，上传xls或xlsx文件" v-model="addForm.file.name"></el-input>
            <upload-excel-component class="flex mrg-top" :before-upload="batchUpload" @submitXlsx="submitXlsx" :loading="!videoFlag">
              <span>{{goodsData != 0 ? goodsData + '%' : ''}}</span>
            </upload-excel-component>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="permitFormVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" size="mini" round @click="getaddWhiteApp">确 定</el-button>
        <el-button v-else type="primary" @click="geteditWhiteApp('ruleForm')" size="mini" round>提交</el-button>
      </div>
    </el-dialog>
    <!-- 添加end -->

    <!-- 删除弹窗start -->
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
    <!-- 删除弹窗end -->
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import { queryWhiteApp, queryIdWhiteApp, addWhiteApp, deleteWhiteApp, editWhiteApp } from "@/api/deployment.js";
import deleteDialog from "@/components/deleteDialog";
import { getBatchTwo } from "@/api/equipment.js";
import UploadExcelComponent from "@/components/UploadExcelSn/index.vue";
import { mapState } from 'vuex'
import tableMini from '@/utils/tableMini.js'
export default {
  mixins: [tableMini],
  components: { dynamicTable, UploadExcelComponent, deleteDialog },
  data() {
    return {
      checkboxVal: ["归属", "批次", "包名", "创建时间"],
      select: "batch", //搜索条件
      //添加按钮控制
      permitFormVisible: false,
      //编辑按钮控制
      editSubjects: true,
      //浏览器专题id
      subjectId: 0,
      //table
      tableData: [],
      listQuery: { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), username: undefined, batch: undefined },
      addForm: { batch: '', file: {}, type: 2, package: '', userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip") },
      lotoptions: [],
      videoFlag: true,
      batchShow: false,
      time: null
    }
  },
  created() {
    this.getTabularData()
    this.getBatchTwos()
  },
  computed: {
    typeControl() {
      return this.addForm.type == 1 ? false : true
    },
    ...mapState({//获取上传滚动条
      goodsData: state => state.user.progress
    })
  },
  methods: {
    //删除按钮事件
    deleteEvents() {
      let params = {
        userId: localStorage.getItem("ID"),
        last_ip: sessionStorage.getItem("Ip"),
        id: this.deleteDialogs.deleteId
      }
      deleteWhiteApp(params).then(res => {
        this.$message.success(res.msg)
        this.getTabularData()
      })
    },
    //根据ID查询信息
    getqueryIdWhiteApp(id) {
      this.editSubjects = false
      this.subjectId = id
      queryIdWhiteApp({ id: id }).then(({ data }) => {
        this.permitFormVisible = true
        console.log('---------',data)
        this.addForm.batch = data.batch_id
        // this.addForm.batch = this.lotoptions.filter(item => {
        //   if (item.batch == data.batch) {
        //     return item.id
        //   }
        // })[0].id
        this.addForm.type = data.type
        data.type == 1 ? this.addForm.package = data.package_name : ''
      }).catch(err => { })
    },
    //编辑信息
    geteditWhiteApp() {
      if (this.addForm.type == 2) {
        if (this.addForm.file instanceof File) {
          if (this.batchShow) {
            this.permitFormVisible = false
          } else {
            this.$message('存在导入文件未上传，请确认是否需要上传。')
          }
        } else {
          this.permitFormVisible = false
        }
      } else {
        this.editWhiteApps()
      }
    },
    //单条编辑功能
    editWhiteApps() {
      this.addForm.id = this.subjectId
      console.log('添加参数', this.addForm)
      editWhiteApp(this.addForm).then(res => {
        this.$message.success(res.msg)
        this.permitFormVisible = false
        this.getTabularData()
      }).catch(err => {
        this.permitFormVisible = false
      })
    },
    //多条SN编辑
    multiediApps() {
      var fd = new FormData()
      fd.append('file', this.addForm.file)
      fd.append('userId', localStorage.getItem("ID"))
      fd.append('last_ip', sessionStorage.getItem("Ip"))
      fd.append('type', this.addForm.type)
      fd.append('batch', this.addForm.batch)
      fd.append('id', this.subjectId)
      editWhiteApp(fd).then(res => {
        console.log('导入成功', res)
        this.batchShow = true
        this.$message.success(res.msg)
        this.videoFlag = true
        this.getTabularData()
        this.permitFormVisible = false
      }).catch(err => {
        this.videoFlag = true
        this.permitFormVisible = false
      })
    },
    //选取文件
    batchUpload(file) {
      this.addForm.file = file
    },
    //添加应用白名单
    getaddWhiteApp() {
      if (this.addForm.type == 2) {
        if (this.addForm.file instanceof File) {
          if (this.batchShow) {
            this.permitFormVisible = false
          } else {
            this.$message('存在导入文件未上传，请确认是否需要上传。')
          }
        } else {
          this.permitFormVisible = false
        }
      } else {
        this.addWhiteApps()
      }
    },
    //单条SN添加
    addWhiteApps() {
      console.log('添加参数', this.addForm)
      addWhiteApp(this.addForm).then(res => {
        this.$message.success(res.msg)
        this.permitFormVisible = false
        this.getTabularData()
      }).catch(err => {
        this.permitFormVisible = false
      })
    },
    //多条SN添加
    multiaddApps() {
      var fd = new FormData()
      fd.append('file', this.addForm.file)
      fd.append('userId', localStorage.getItem("ID"))
      fd.append('last_ip', sessionStorage.getItem("Ip"))
      fd.append('type', this.addForm.type)
      fd.append('batch', this.addForm.batch)
      addWhiteApp(fd).then(res => {
        console.log('导入成功', this.addForm.type)
        this.batchShow = true
        this.$message.success(res.msg)
        this.videoFlag = true
        this.getTabularData()
        this.permitFormVisible = false
      }).catch(err => {
        this.videoFlag = true
        this.permitFormVisible = false
      })
    },
    submitXlsx(event) {
      this.videoFlag = false
      if (this.editSubjects) {
        this.multiaddApps()
      } else {
        this.multiediApps()
      }
    },
    getTabularData() {
      queryWhiteApp(this.listQuery).then(res => {
        this.tableData = res.data
        this.total = res.total
      }).catch(err => {
        this.tableData = []
        this.total = 0
      })
    },
    btnaddBrand() {
      this.editSubjects = true
      this.permitFormVisible = true
    },
    //根据ID获取批次列表
    getBatchTwos() {
      let data = { userId: localStorage.getItem("ID") }
      getBatchTwo(data).then(res => {
        this.lotoptions = res.data
      }).catch(err => {
        this.lotoptions = []
      })
    },
    addFormclose() {
      this.$nextTick(() => {
        this.addForm = this.$options.data().addForm
        this.videoFlag = true
        this.batchShow = false
      })
    },
    //批次创立更新导入模板
    handleDownload() {
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = ["应用包名"];
        const filterVal = ["应用包名"];
        const list = [{ "应用包名": 'com.jiongji.andriod.card' }]
        const data = this.formatJson(filterVal, list);
        excel.export_json_to_excel({ header: tHeader, data, filename: ' 应用白名单辅助管理模板' });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    }
  }
}
</script>